package com.seek.educms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.seek.educms.entity.CrmBanner;
import com.seek.educms.mapper.CrmBannerMapper;
import com.seek.educms.service.CrmBannerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 首页banner表 服务实现类
 * </p>
 *
 * @author wml
 * @since 2022-02-10
 */
@Service
public class CrmBannerServiceImpl extends ServiceImpl<CrmBannerMapper, CrmBanner> implements CrmBannerService {

    @Autowired
    private RedisTemplate redisTemplate;

    // 查询所有 banner
    @Cacheable(value = "banner", key = "'selectIndexList'")
    @Override
    public List<CrmBanner> getAllBanner() {
        return baseMapper.selectList(null);
    }

    // 根据 isShow 字段，查询 banner
    @Cacheable(value = "banner", key = "'selectIndexList'")
    @Override
    public List<CrmBanner> getAllBannerByIsShow() {
        QueryWrapper<CrmBanner> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_show", 1);
        return baseMapper.selectList(queryWrapper);
    }

    // 新增Banner
    @Override
    public void saveBanner(CrmBanner banner) {
        baseMapper.insert(banner);
        if (banner.getIsShow() == 1) {
            redisTemplate.delete("banner::selectIndexList");
        }
    }

    // 修改Banner
    @Override
    public void updateBannerById(CrmBanner banner) {
        Integer isShow = baseMapper.selectById(banner.getId()).getIsShow();
        Integer nowIsShow = banner.getIsShow();
        baseMapper.updateById(banner);
        if (isShow != nowIsShow) {
            redisTemplate.delete("banner::selectIndexList");
        }
    }

    // 删除Banner
    @Override
    public void removeBannerById(String id) {
        CrmBanner banner = baseMapper.selectById(id);
        baseMapper.deleteById(id);
        if (banner.getIsShow() == 1) {
            redisTemplate.delete("banner::selectIndexList");
        }
    }
}
